package com.tuzhi.sys.scurity;

import com.tuzhi.base.redis.MyRedisTemplate;

import com.tuzhi.common.domain.LoginUserBO;
import com.tuzhi.security.service.impl.TokenStoreServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 这个类继承重写了tuzhi-security中的 TokenStoreServiceImpl
 * 如：public LoginUserBO getLoginUser(String token) 在 TokenStoreServiceImpl 是获取Map缓存中的用户
 * 但这里重写了，是获取redis缓存中的用户
 * <p>
 * TokenStoreServiceImpl 是对Map中的数据操作
 * <p>
 * MyTokenStoreServiceImpl 是对Redis的数据操作
 */
@Primary
@Component
public class MyTokenStoreServiceImpl extends TokenStoreServiceImpl {

    @Autowired
    MyRedisTemplate redisCache;

    @Override
    public LoginUserBO getLoginUser(String token) {
        return redisCache.getCacheObject(token);
    }

    @Override
    public void delLoginUser(String key) {
        redisCache.del(key);
    }

    @Override
    public void storeLoginUser(LoginUserBO loginUserBO) {
        int expireTime = getExpireTime(loginUserBO);
        String key = getTokenKey(loginUserBO.getJti());
        redisCache.setCacheObject(key, loginUserBO, expireTime, TimeUnit.SECONDS);
    }

    @Override
    public <T> void setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit) {

        redisCache.setCacheObject(key, value, timeout, timeUnit);
    }

    static private int getExpireTime(LoginUserBO loginUserBO) {

        long ts = loginUserBO.getExpireTime() - loginUserBO.getLoginTime();
        ts = ts / 1000;
        return Long.valueOf(ts).intValue();
    }

    public static void main(String[] args) {
        LoginUserBO loginUserBO = new LoginUserBO();
        loginUserBO.setLoginTime(1676448276046l);
        loginUserBO.setExpireTime(1676450076046l);
        System.out.printf("aa" + getExpireTime(loginUserBO));

    }
}
